﻿using UnityEngine;
using UnityEngine.UI;
using zFrame.Networks;

namespace zFrame.Example
{
    public class LoginPage : MonoBehaviour
    {

        #region About Password
        public InputField phoneNo;
        public InputField password;
        public Button submmitPsw;

        #endregion

        public void Awake()
        {
            submmitPsw.onClick.AddListener(OnPswSubmmit);
        }
        private void Start()
        {
            phoneNo.text = "18524568546";
            password.text = "123456";
            NetworkClient.Connect();
        }

       

        public void OnEnable()
        {
            NetworkClient.AddListener( ResponseCode.Login, LoginCallBack);
        }
        public void OnDisable()
        {
            NetworkClient.RemoveListener(ResponseCode.Login, LoginCallBack);
        }

        private void LoginCallBack(Response response)
        {
            //成功 跳转到首页
            ResponseLoginVo responseMsg = JsonUtility.FromJson<ResponseLoginVo>(response.message);
            if (null == responseMsg)
            {
                Debug.LogError("登录返回数据异常！");
                return;
            }
            if (responseMsg.code == 200 && responseMsg.data.isLogin)
            {
                CommonModel.Instance.AccountInfo = responseMsg.data;
                Debug.Log("获取到登录成功后的数据！");
                OnLoginSuccess();
            }
            else if (responseMsg.code == 200 && responseMsg.data.msg == 3)
            {
                //用户名错误
                Debug.Log("该账户不存在");

            }
            else if (responseMsg.code == 200 && responseMsg.data.msg == 2)
            {
                //密码错误
                Debug.Log("密码不正确 ");
            }
            else
            {
                Debug.Log("网络错误");
            }
        }

        private void OnPswSubmmit()
        {
            Debug.LogFormat("提交了登录账号:【{0}】，密码 :【{1}】 ", phoneNo.text, password.text);
            if (!NetworkClient.isConnected)
            {
                Debug.Log("网络异常无法登录!");
            }
            else
            {
                OnLogin(phoneNo.text, password.text);
            }
        }

        private void OnLogin(string username, string password)
        {
            Debug.Log("Connected with socket");
            AccountVo loginVo = new AccountVo();
            loginVo.account = username;
            loginVo.password = password;
            loginVo.isfaceLogin = "0";
            Request request = new Request(loginVo,  RequestCode.Login);
            NetworkClient.SendMessage(request);
        }

        void OnLoginSuccess()
        {
            Debug.Log("----------------------<color=green>登录成功</color>----------------------");
        }

    }
}
